from java.awt import BorderLayout
from javax.swing import JComponent
from javax.swing.text import StyleConstants, StyleContext
from javax.swing.event import HyperlinkEvent, HyperlinkListener

try:
	import javax.jnlp.BasicService as BasicService
	import javax.jnlp.ServiceManager as ServiceManager
except:
	pass

class SchmuckUrlListener(HyperlinkListener):
	def __init__(self):
		try:
			self.basic_service = ServiceManager.lookup("javax.jnlp.BasicService")
		except:
			pass

	def hyperlinkUpdate(self, evt):
		if(evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED):
			try:
				self.basic_service.showDocument(evt.getURL())
			except:
				pass

class SchmuckOutputComponent(JComponent):
	def __init__(self):
		self.setLayout(BorderLayout())
		self.pane = PandoraTextPane()
		self.doc = self.pane.getStyledDocument()
		self.pane.setEditable(False)
		self.pane.addHyperlinkListener(SchmuckUrlListener())
		self.initialize_styles()
		
		# Establish the subset of filters which we'll be using
		self.filter = SchmuckTextFilter()
		if(applet.getProperty("filters")):
			for filter_name in applet.getProperty("filters").split(','):
				if(filter_name in schmuck_text_filters):
					self.filter.add_filter(schmuck_text_filters[filter_name])
		
		self.scrollpane = JScrollPane(self.pane)
		self.scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
		
		self.add(self.scrollpane, BorderLayout.CENTER)

	## Initialize some basic styles used by this text pane
	def initialize_styles(self):
		default_style = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE)

		standard_style = self.doc.addStyle("regular", default_style)
		StyleConstants.setFontFamily(standard_style, "Courier New")
		StyleConstants.setFontSize(standard_style, 12)

		s = self.doc.addStyle("bold", standard_style)
		StyleConstants.setBold(s, True)

		s = self.doc.addStyle("italic", standard_style)
		StyleConstants.setItalic(s, True)

		s = self.doc.addStyle("underline", standard_style)
		StyleConstants.setUnderline(s, True)

	## When we receive a message, apply any filters to it and render it
	def receive_line(self, socket_id, s):
		# Run all received text through the filters and add it to the pane
		text = self.filter.filter_text(socket_id, s)
		for style, string in text:
			self.pane.addStyledText(string, self.doc.getStyle(style))

		self.pane.addNewline()
		self.pane.setCaretPosition(self.doc.getLength())
		self.scrollpane.getHorizontalScrollBar().setValue(0)
